package com.skyon.sdk;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.skyon.sdk.bean.ResultBean;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by chen on 2018/5/5.
 */

public class SkyonSdk {

    private static Application mapplication;
    private static boolean collectOnFirstInstall = true;
    private static boolean collectOnStart = true;
    private static boolean cyclicCollection = true;
    private static boolean collectionOnEvent = true;
    protected static int CyclicCollectionInterval = 60000;
    protected static int waitForPMCheck = 15000;
    private static int cyclicDefault = 60000;
    protected static boolean isCollectD = false;
    protected static boolean isSetByUser = false;
    protected static String userId = "";
    protected static String appKey = "";
    protected static String appId = "";
    private static boolean isInit = false;
    public static boolean isTmpFirst = false;
    private static final Timer timer = new Timer();
    private static TimerTask task;
    public static boolean openErrorCollection = true;

    public static void setCyclicCollectionInterval(int cyclicCollectionInterval) {
        isSetByUser = true;
        CyclicCollectionInterval = cyclicCollectionInterval;
    }

    public static void setCollectOnFirstInstall(boolean collectOnFirstInstall) {
        isSetByUser = true;
        SkyonSdk.collectOnFirstInstall = collectOnFirstInstall;
    }

    public static void userDefEvent(final Context context, final String json, final String eventNum, final String eventComment) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ResultBean resultBean = MSUCommon.resultBean.setUserDefInfo(context, new ResultBean(), json, eventNum, eventComment);
                        String s = resultBean.toString();
                        MSUHttpUtils.mPost(s);
                        Log.d("SkyonSdk:", "userDefEvent......" + s);
                    }
                });
                Looper.loop();
            }
        }).start();
    }

    protected static String getServerAddress() {
        return serverAddress;
    }

    public static void setServerAddress(String serverAddress) {
        isSetByUser = true;
        SkyonSdk.serverAddress = serverAddress;
    }

    protected static String serverAddress = null;

    protected static boolean isIsCollectD() {
        return isCollectD;
    }

    public static void setCollectionOnEvent(Boolean isCollectionOnEvent) {
        isSetByUser = true;
        collectionOnEvent = isCollectionOnEvent;
    }

    public static void setCyclicCollection(Boolean isCyclicCollectionb) {
        isSetByUser = true;
        cyclicCollection = isCyclicCollectionb;
    }

    public static void setCollectOnStart(Boolean isCollectOnStart) {
        isSetByUser = true;
        collectOnStart = isCollectOnStart;
    }

    public static void setUserId(String userId) {
        isSetByUser = true;
        SkyonSdk.userId = userId;
        if (mapplication != null) {
            MSUCommon.setUserID47(mapplication, userId);
        }
    }

    public static void setAppId(String appId) {
        isSetByUser = true;
        SkyonSdk.appId = appId;
        if (mapplication != null) {
            MSUCommon.setAppId64(mapplication, appId);
        }
    }

    public static void setAppKey(String appKey) {
        isSetByUser = true;
        SkyonSdk.appKey = appKey;
        if (mapplication != null) {
            MSUCommon.setKey44(mapplication, appKey);
        }
    }

    public static Class<?> getMyWBClass() {
        Class<?> aClass = null;
        try {
            return mapplication.getClassLoader().loadClass("android.webkit.WebView");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return aClass;
    }

    public static void init(final Application application) {

        if (isInit == true) {
            return;
        }
        mapplication = application;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            isTmpFirst = true;
        }
        if (userId != null && !userId.equals("")) {
            MSUCommon.setUserID47(mapplication, userId);
        }
        if (appKey != null && !appKey.equals("")) {
            MSUCommon.setKey44(mapplication, appKey);
        }
        if (appId != null && !appId.equals("")) {
            MSUCommon.setAppId64(mapplication, appId);
        }
        if (!isSetByUser) {
            loadConf(mapplication);
        }
        if (collectionOnEvent) {
            application.registerActivityLifecycleCallbacks(new MSUActivityLifecycle());
        }

        if (openErrorCollection) {
            MSUCrashHanderUtil.getInstance().init(application);
        }
        application.registerReceiver(mBroadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        if (collectOnFirstInstall) {
            if (MSUCommon.isFirst(application)) {
                //初次安装采集
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!isTmpFirst) {
                                Thread.sleep(waitForPMCheck);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Looper.prepare();
                        ResultBean firstBean = MSUCommon.resultBean.setUpFirstInfo(mapplication, new ResultBean());
                        String s = firstBean.toString();
                        MSUHttpUtils.mPost(s);
                        Log.d("SkyonSdk:", "isFirst......" + s);
                        Looper.loop();
                    }
                }).start();
                MSUCommon.setFirst(application);
            }
        }
        //启动采集
        if (collectOnStart) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (!isCollectD) {
                            Thread.sleep(3000);
                        }
                        if (!isTmpFirst) {
                            Thread.sleep(waitForPMCheck);
                        }
                    } catch (InterruptedException e) {
                    }
                    Looper.prepare();
                    ResultBean startBean = MSUCommon.resultBean.setUpStartInfo(application, new ResultBean());
                    String s = startBean.toString();
                    Log.d("SkyonSdk:", "collectOnStart......" + s);
                    MSUHttpUtils.mPost(s);
                    Looper.loop();
                }
            }).start();
        }

        final Handler cyclicCollectionHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                ResultBean cyclicBean = MSUCommon.resultBean.setUpCyclicInfo(application, new ResultBean());
                String s = cyclicBean.toString();
                MSUHttpUtils.mPost(s);
                Log.d("SkyonSdk:", "cyclicCollection......" + s);
                super.handleMessage(msg);
            }
        };
        if (cyclicCollection) {
            task = new TimerTask() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Message message = new Message();
                    message.what = 1;
                    cyclicCollectionHandler.sendMessage(message);
                }
            };
            timer.schedule(task, cyclicDefault, CyclicCollectionInterval < cyclicDefault ? cyclicDefault : CyclicCollectionInterval);
        }
        isInit = true;

    }

    private static String loadConf(Application mapplication) {
        try {
            Properties properties = new Properties();
            InputStream is = mapplication.getAssets().open("SkyonSdkConfig.txt");
            properties.load(is);
            String collectOnFirstInstall = properties.getProperty("collectOnFirstInstall");
            if (collectOnFirstInstall != null) {
                setCollectOnFirstInstall(Boolean.parseBoolean(collectOnFirstInstall));
            }
            String collectOnStart = properties.getProperty("collectOnStart");
            if (collectOnStart != null) {
                setCollectOnStart(Boolean.parseBoolean(collectOnStart));
            }
            String collectionOnEvent = properties.getProperty("collectionOnEvent");
            if (collectionOnEvent != null) {
                setCollectionOnEvent(Boolean.parseBoolean(collectionOnEvent));
            }
            String cyclicCollection = properties.getProperty("cyclicCollection");
            if (cyclicCollection != null) {
                setCyclicCollection(Boolean.parseBoolean(cyclicCollection));
            }
            String cyclicCollectionInterval = properties.getProperty("cyclicCollectionInterval");
            if (cyclicCollectionInterval != null) {
                setCyclicCollectionInterval(Integer.parseInt(cyclicCollectionInterval));
            }
            String serverAddress = properties.getProperty("serverAddress");
            if (serverAddress != null) {
                setServerAddress(serverAddress);
            }
            String appKey = properties.getProperty("appKey");
            if (appKey != null && !appKey.equals("")) {
                setAppKey(appKey);
            }
            String userId = properties.getProperty("userId");
            if (userId != null && !userId.equals("")) {
                setUserId(userId);
            }
            String appId = properties.getProperty("appId");
            if (appId != null && !appId.equals("")) {
                setAppId(appId);
            }
        } catch (Exception e) {
            return null;
        }
        return "";
    }


    /**
     * 获取电池容量 mAh
     *
     * @param context
     * @return
     */
    private static double getBatteryCapacity(Context context) {
        Object mPowerProfile;
        double batteryCapacity = 0;
        final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

        try {
            mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
                    .getConstructor(Context.class)
                    .newInstance(context);

            batteryCapacity = (double) Class
                    .forName(POWER_PROFILE_CLASS)
                    .getMethod("getBatteryCapacity")
                    .invoke(mPowerProfile);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return batteryCapacity;
    }

    // 声明广播接受者对象
    protected static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                // 得到电池状态：
                int status = intent.getIntExtra("status", 0);
                // 得到健康状态：
                int health = intent.getIntExtra("health", 0);
                // boolean类型
//                boolean present = intent.getBooleanExtra("present", false);
                // 得到电池剩余容量
                int level = intent.getIntExtra("level", 0);
                // 得到电池最大值。通常为100。
                int scale = intent.getIntExtra("scale", 0);
                double temperature = intent.getIntExtra("temperature", 0) / 10.0;  //电池温度(数值)
                // 充电方式：　BatteryManager.BATTERY_PLUGGED_AC：AC充电。　BatteryManager.BATTERY_PLUGGED_USB：USB充电。
                int plugged = intent.getIntExtra("plugged", 0);

                // 得到电池状态
                String statusString = "";
                // 根据状态id，得到状态字符串
                switch (status) {
                    case BatteryManager.BATTERY_STATUS_UNKNOWN:
                        statusString = "未知状态";
                        break;
                    case BatteryManager.BATTERY_STATUS_CHARGING:
                        statusString = "充电状态";
                        break;
                    case BatteryManager.BATTERY_STATUS_DISCHARGING:
                        statusString = "放电状态";
                        break;
                    case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                        statusString = "未充满";
                        break;
                    case BatteryManager.BATTERY_STATUS_FULL:
                        statusString = "充满";
                        break;
                }
                //得到电池的寿命状态
                String healthString = "";
                //根据状态id，得到电池寿命
                switch (health) {
                    case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                        healthString = "unknown";
                        break;
                    case BatteryManager.BATTERY_HEALTH_GOOD:
                        healthString = "good";
                        break;
                    case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                        healthString = "overheat";
                        break;
                    case BatteryManager.BATTERY_HEALTH_DEAD:
                        healthString = "dead";
                        break;
                    case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                        healthString = "voltage";
                        break;
                    case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                        healthString = "unspecified failure";
                        break;
                }
                double batteryCapacity = getBatteryCapacity(context);
                String str39 = statusString;
                String str40 = String.valueOf(level);
                String str41 = batteryCapacity * (level / 100.0) + "/" + batteryCapacity;
                String str42 = String.valueOf(temperature);
                String str56 = plugged != 0 ? "ture" : "false";

                MSUCommon.resultBean.setStatus39(str39);
                MSUCommon.resultBean.setLevel40(str40);//剩余电量
                MSUCommon.resultBean.setScale41(str41);
                MSUCommon.resultBean.setTemperature42(str42);
                MSUCommon.resultBean.setIsCharge56(str56);
                if (!isCollectD) {
                    MSUCommon.setBatteryInfo(context, str39 + "-" + str40 + "-" + str41 + "-" + str42 + "-" + str56);
                    isCollectD = true;
                }

            }
        }
    };

    protected static void h5LoadEvent(final String url, final long start, final String checkId, final String lgnUr, final String title) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss", Locale.CHINA);
                final ResultBean mResultBean = new ResultBean();
                mResultBean.setIMEI20(MSUCommon.getIMEI20(mapplication));
                mResultBean.setViewPage58(url);
                mResultBean.setViewVisitTime59(formatter.format(start));
                mResultBean.setCollectEventType62("7");
                mResultBean.setCollectType63("H5页面加载采集");
                mResultBean.setAppId64(MSUCommon.getAppId64(mapplication));
                mResultBean.setCheckId65(checkId);
                mResultBean.setLgnUr66(lgnUr);
                mResultBean.setH5Title68(title);
                MSUHttpUtils.mPost(mResultBean.toString());
                Log.d("SkyonSdk:", "h5LoadEvent......" + mResultBean.toString());
            }
        }).start();
    }

}
